package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.qo.JsonResult;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.EmployeeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @RequestMapping("/loginUser")
    @ResponseBody
    public JsonResult login(String username, String password) {
            /*try {
                Employee employee = employeeService.login(username, password);
                //session.setAttribute("EMPLOYEE_IN_SESSION",employee);
                UserContext.setCurrentEmployee(employee);
                if (!employee.isAdmin()) {

                    //登录成功后吧次员工对应权限数据放到session中
                    //session.setAttribute("EXPRESSIONS_IN_SESSION",permissionService.queryByEmployeeId(employee.getId()));
                    UserContext.setExpression((Permission) permissionService.queryByEmployeeId(employee.getId()));
                }

                return new JsonResult(true, "登录成功");
            } catch (Exception e){
                e.printStackTrace();
                return new JsonResult(false,e.getMessage());
            }*/


        //获取主体对象
        //使用shiro进行验证
        Md5Hash md5Hash = new Md5Hash(password, username);
        UsernamePasswordToken token = new UsernamePasswordToken(username, md5Hash.toString());
        try {
            SecurityUtils.getSubject().login(token);
            Employee employee = EmployeeUtil.getEmployee();
            if (!employee.isStatus()) {
                return new JsonResult(false, "账号已禁用!");
            }
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return new JsonResult(false, "密码错误");

        }


        return new JsonResult(true, "登录成功");
    }
}
